/*****************************************************************************************
**  Author:jxx 2022
**  QQ:283591387
**完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
**常用示例见：http://v2.volcore.xyz/document/vueDev
**后台操作见：http://v2.volcore.xyz/document/netCoreDev
*****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import modelHeader from "./goodsInCom.vue"
let extension = {
  components: {
    //查询界面扩展组件
    gridHeader: '',
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody: '',
    modelFooter: ''
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: { view: [], box: [], detail: [] }, //扩展的按钮

  methods: {
    //下面这些方法可以保留也可以删除
    onInit() {  //框架初始化配置前，
      //示例：在按钮的最前面添加一个按钮
      //   this.buttons.unshift({  //也可以用push或者splice方法来修改buttons数组
      //     name: '按钮', //按钮名称
      //     icon: 'el-icon-document', //按钮图标vue2版本见iview文档icon，vue3版本见element ui文档icon(注意不是element puls文档)
      //     type: 'primary', //按钮样式vue2版本见iview文档button，vue3版本见element ui文档button
      //     onClick: function () {
      //       this.$Message.success('点击了按钮');
      //     }
      //   });

      //示例：设置修改新建、编辑弹出框字段标签的长度
      // this.boxOptions.labelWidth = 150;
      this.setFiexdSearchForm(true);
      this.detailOpen = true

      this.editFormOptions.forEach(option => {

        option.forEach(item => {

          if (item.field == "GoodsIn_client") {

            item.remote = true
            // item.type="select"
            // item.url='api/Sys_Dictionary/GetSearchDictionary'//从指定url搜索 返回格式必须是[{key:'xxxx',value:'xxx'}]
            item.extra = {
              icon: "el-icon-zoom-in",
              text: "选择客户",
              style: "color:#3a8ee6;font-size:13px;curspr:default",
              click: () => {
                this.$refs.modelHeader.open()
              }
            }
          }
          //测试输入事件
          // if (item.field == "GoodsIn_num") {
          //   item.onKeyPress = $event => {
          //     console.log("$event1", $event);
          //     if ($event.keyCode == 13) { console.log("回车事件"); return; }
          //     let val = this.editFormFields.GoodsIn_num + $event.key;
          //     console.log("当前输入的值：" + val)
          //   }
          // }
        })
      })
      //获取当前用户信息
      // let url = "api/q_goodsOut_class/getUserInfo"
      // this.http.post(url, {}, "").then(reslut => {
      //   try {
      //     this.user_Id = reslut.user_Id
      //   } catch (error) {
      //     console.error(error)
      //   }
      // })
      this.UpdateState = false //自定义用户编辑权限
      if (this.filterPermission("q_goodsIn_class", 'Update')) {
        //to do...
        console.log("Update")
        this.UpdateState = true
      }
    },
    async onInited() {
      //框架初始化配置后
      //如果要配置明细表,在此方法操作
      this.detailOptions.columns.forEach(column => {
        // if (column.field == "GoodsInList_sub") {
        //   this.inputDom = document.querySelector(".el-table__body-wrapper .el-input__inner")
        // }
        if (column.field == "GoodsInList_num" || column.field == "GoodsInList_price") {
          column.summary = true

        }
        // if (column.field == "GoodsInList_sub") {
        //   // column.remote = true
        //   // column.change = () => { console.log(1) }
        // }
      });
      let indexNum = this.detailOptions.buttons.findIndex(item => item.name == "添加行")
      if (indexNum != "-1") {
        this.detailOptions.buttons.splice(indexNum, 1)
      }
      this.detailOptions.buttons.unshift({
        name: "选择数据",//按钮名称
        icon: 'el-icon-plus',//按钮图标，参照iview图标
        type: 'primary',
        plain: true,
        onClick: function () { //触发事件
          this.$refs.modelHeader.detailOpen()
        }
      })

      //明细表编辑结束后触发
      // this.detailOptions.endEditAfter = (row, column, index) => {
      //  alert("是结束吗")
      //   return true;//返回false不会进行编辑
      // }
      // //明细表点击表格时触发编辑方法
      this.detailOptions.beginEdit = (row, column, index) => {
        if (this.currentAction != 'Add' && !this.statusOff) {
          return false
        }
        //------test 限制同一用户编辑
        if (this.currentAction == 'Add') {
          //可以继续
        } else if (this.currentAction == 'Update' && !this.statusOff || !this.user_id_boole) {
          return false
        }
        //------test 限制同一用户编辑---end
        this.detailOptions.columns.forEach(item => {
          if (item.field == "WHSE_name") {
            if (!row.GoodsInList_sub) {
              return
            }
            let selectUrl = `api/q_warehouse_locationList/getgoodslocation?bm=${row.GoodsInList_sub}`
            item.bind.data.forEach((d) => {
              d.hidden = true;
            });
            this.http.post(selectUrl, {}, "").then(reslut => {
              item.bind.data.forEach(d => {
                d.hidden = true
              })
              item.bind.data.forEach(d => {
                reslut.rows.forEach(j => {
                  if (d.key == j.WHSE_no) {
                    d.hidden = false
                  }
                })
              })
              row.WHSE_name = item.bind.data.filter(x => x.hidden == false)[0].key
            })
          }
        })
        let rows = document.querySelectorAll(".grid-detail .el-table__body .el-table__row")

        setTimeout(() => {
          //编码搜商品,此功能已禁用,可以请求前增加判断列表中是否已含有已编码
          let testInputDom = rows[index].querySelectorAll("td")[1].querySelector("input")
          if (testInputDom) {
            testInputDom.addEventListener("keyup", (e) => {
              if (e.key == "Enter") {
                let url = `api/q_goodsInList_class/getGoosData?dm=${testInputDom.value}`
                this.http.post(url, {}, "").then(reslut => {
                  let data = reslut[0]
                  row.GoodsInList_name = data.Item_name
                  row.GoodsInList_price = data.Sale_price
                  row.GoodsInList_size = data.Item_size
                  row.WHSE_name = null

                }).catch(error => {
                  row.GoodsInList_name = null
                  row.GoodsInList_price = null
                  row.GoodsInList_size = null
                  row.WHSE_name = null
                  row.Remark = null
                  this.$message.error("暂无此编码商品信息")
                })
              }
            })
          }
        }, 0)
        return true;//返回false不会进行编辑
      }
    },
    // 自定义按钮事件
    addRowFn() { },
    async getDetailRowData(param) {
      alert("getDetailRowData")
      if (!this.inputDom) {
        // console.log("内里3");
        this.inputDom = document.querySelector(".el-table__body-wrapper .el-input__inner")
        this.inputDom.addEventListener("blur", () => {
          // console.log("失焦");
          this.inputDom = null
        })
        await this.inputDom.addEventListener('keydown', (event) => {
          if (event.code == "Enter") {
            // console.log("按下了Enter4");
            let url = `api/q_goodsInList_class/getGoosData?dm=${param.GoodsInList_sub}`
            this.http.post(url, {}).then(reslut => {
              let data = reslut[0]
              param.GoodsInList_name = data.Item_name
              param.GoodsInList_price = data.Sale_price
              param.GoodsInList_size = data.Item_size
              param.WHSE_name = null
              // console.log("param", param);
            }).catch(error => {
              param.GoodsInList_name = null
              param.GoodsInList_price = null
              param.GoodsInList_size = null
              param.WHSE_name = null
              param.Remark = null
              this.$message.error("暂无此编码商品信息")
              setTimeout(() => {
                this.inputDom = null
              }, 1000)
            })

          }
        });
      }
    },

    searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      if(this.$route.path != "/q_goodsIn_class"){
        // param.wheres = param.wheres.filter(item => item.name != "当前页面的ID")
        this.$route.query={}
      }
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    async addBeforeAsync(formData) {
      return this.getSummary(formData)
    },
    addBefore(formData) {
      //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
      return true;
    },
    async updateBeforeAsync(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      let url = `api/q_goodsIn_class/audit?auditReason=&auditStatus=0`
      return this.getSummary(formData)
    },
    async getSummary(formData) {
      let detailRowData = this.$refs.detail.rowData
      let num = 0
      let summaryPrc = 0
      let summaryNum = 0
      await detailRowData.forEach(item => {
        summaryPrc += item.GoodsInList_price * item.GoodsInList_num
        summaryNum += +item.GoodsInList_num
        if (item.GoodsInList_sub && item.GoodsInList_name && item.GoodsInList_num && item.WHSE_name) num++
      })
      formData.mainData.GoodsIn_num = summaryNum
      formData.mainData.GoodsIn_money = summaryPrc


      if (detailRowData.length == num) {
        return true
      } else {
        this.$message.error("请正确选择商品")
        return false
      }
    },
    rowClick({ row, column, event }) {
      //查询界面点击行事件
      // this.$refs.table.$refs.table.toggleRowSelection(row); //单击行时选中当前行;
    },
    detailRowClick({ row, column, event }) {
      //编辑弹出框从表table点击行选中当前行，没有从表的不用管
      // this.$refs.detail.$refs.table.toggleRowSelection(row);
      if (this.currentAction == 'Add' || this.statusOff && this.user_Id == row.CreateID) {
        if (column.property == "GoodsInList_price" || column.property == "GoodsInList_num" || column.property == "WHSE_name" || column.property == "Remark") {
          let dom = event.target
          setTimeout(() => {
            let inpDom = dom.querySelector("input")
            inpDom.focus()
          }, 0)
        }
      }
    },
    // 控制新建编辑的弹出框-----
    async getModuleStatus() {
      this.boxButtons[0].hidden = false //弹出框的保存按钮
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          this.detailOptions.buttons.forEach(item => {
            item.hidden = false
          })
          if (x.field == "GoodsIn_client") {
            x.extra = {
              icon: "el-icon-zoom-in",
              text: "选择客户",
              style: "color:#3a8ee6;font-size:13px;cursor:default",
              click: () => {
                this.$refs.modelHeader.open()
              }
            }
          }

          if (x.field == "GoodsIn_client" || x.field == "Remark") {
            x.disabled = false
          }
        })
      })
    },
    // 控制新建编辑的弹出框-----end
    async modelOpenBefore(row) {
      this.user_id_boole =this.user_Id == row.CreateID
      if (this.currentAction != 'Add') {
        if (this.boxButtons[0]) {
          this.boxButtons[0].hidden = true
        }
        this.editFormOptions.forEach(item => {
          item.forEach(x => {
            this.detailOptions.buttons.forEach(item => {
              item.hidden = true
            })
            if (x.field == "GoodsIn_client" || x.field == "Remark") {
              x.extra = null
              x.disabled = true
            }
          })
        })
      }
      // 新建
      if (this.currentAction == 'Add') {
        this.getModuleStatus()
      } else if (this.currentAction == 'update' && this.UpdateState) {
        let url = "api/Sys_WorkFlow/getSteps?tableName=q_goodsIn_class"
        await this.http.post(url, [row.GoodsIn_Id], "").then(reslut => {
          try {
            this.statusOff = reslut.list[1].isCurrent
            if (this.statusOff&& this.user_id_boole) {
              this.getModuleStatus()
            }
          } catch (error) {
            console.log("错误", error);
          }
        })
      }
    },
  }
};
export default extension;
